package com.wuhanins.insmytestdemo.domainService.provider.utils;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.graphics.Color;
import android.location.LocationManager;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.blankj.utilcode.util.TimeUtils;
import com.wuhanins.common.utils.INSLog;
import com.wuhanins.common.utils.ToastUtil;
import com.wuhanins.insmytestdemo.R;

import java.util.List;

/**
 * Created by Logan on 2019/4/1.
 * <p>
 * 位置获取工具(基于高德地图) https://lbs.amap.com/api/android-location-sdk/guide/android-location/getlocation
 */

public class AMapLocationUtil {

    private static final String NOTIFICATION_CHANNEL_NAME = "BackgroundLocation";
    private NotificationManager notificationManager = null;
    boolean isCreateChannel = false;
    private AMapLocationClient mLocationClient;

    public void startForLocation(AMapLocationClient mLocationClient, Context mAct, int monitorTime) {
        //初始化定位
//        mLocationClient = new AMapLocationClient(mAct.getApplicationContext());
        mLocationClient.enableBackgroundLocation(2001, buildNotification(mAct));
        //设置定位回调监听
        mLocationClient.setLocationListener(new AMapLocationListener() {
            @Override
            public void onLocationChanged(AMapLocation aMapLocation) {
                double sixLat = aMapLocation.getLatitude();
                double sixLon = aMapLocation.getLongitude();
                String address = aMapLocation.getAddress();
                if (address == null) {
                    address = "";
                }
                String sb = sixLat + "," + sixLon;
                if ("".equals(address)) {
                    sb = "";
                    ToastUtil.show(mAct, "定位出错");
                }
//                ToastUtil.show(mAct, address);
                String location = address;
                String nowDate = TimeUtils.date2String(TimeUtils.getNowDate());
                if (sixLat == 0 && sixLon == 0) {
                    return;
                }
//                MainDomainService.getCreate(nowDate, sixLat, sixLon).run();
                INSLog.e("logan", "经度:" + sixLat + " 纬度:" + sixLon);
                INSLog.e("logan", "时间:" + nowDate);
                INSLog.e("logan", "地点:" + location);
            }
        });
        //声明AMapLocationClientOption对象
        //初始化AMapLocationClientOption对象
        final AMapLocationClientOption mLocationOption = new AMapLocationClientOption();
        /**
         * 设置定位场景，目前支持三种场景（签到、出行、运动，默认无场景）
         */
        mLocationOption.setLocationPurpose(AMapLocationClientOption.AMapLocationPurpose.SignIn);
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);//可选，设置定位模式，可选的模式有高精度、仅设备、仅网络。默认为高精度模式
        mLocationOption.setGpsFirst(false);//可选，设置是否gps优先，只在高精度模式下有效。默认关闭
        mLocationOption.setHttpTimeOut(2000);//可选，设置网络请求超时时间。默认为30秒。在仅设备模式下无效
        if (monitorTime == 0) {
            mLocationOption.setInterval(10 * 1000 * 60);//可选，设置定位间隔。默认为10秒
        } else {
            mLocationOption.setInterval(monitorTime * 1000 * 60);//可选，设置定位间隔。
        }
        mLocationOption.setNeedAddress(true);//可选，设置是否返回逆地理地址信息。默认是true
        mLocationOption.setOnceLocation(false);//可选，设置是否单次定位。默认是false
        mLocationOption.setOnceLocationLatest(false);//可选，设置是否等待wifi刷新，默认为false.如果设置为true,会自动变为单次定位，持续定位时不要使用
        AMapLocationClientOption.setLocationProtocol(AMapLocationClientOption.AMapLocationProtocol.HTTP);//可选， 设置网络请求的协议。可选HTTP或者HTTPS。默认为HTTP
        mLocationOption.setSensorEnable(false);//可选，设置是否使用传感器。默认是false
        mLocationOption.setWifiScan(true); //可选，设置是否开启wifi扫描。默认为true，如果设置为false会同时停止主动刷新，停止以后完全依赖于系统刷新，定位位置可能存在误差
        mLocationOption.setLocationCacheEnable(true); //可选，设置是否使用缓存定位，默认为true
        mLocationOption.setGeoLanguage(AMapLocationClientOption.GeoLanguage.DEFAULT);//可选，设置逆地理信息的语言，默认值为默认语言（根据所在地区选择语言）
        if (null != mLocationClient) {
            mLocationClient.setLocationOption(mLocationOption);
            //设置场景模式后最好调用一次stop，再调用start以保证场景模式生效
            mLocationClient.stopLocation();
            mLocationClient.startLocation();
        }
    }

    public void disableBackgroundLocation() {
        if (mLocationClient != null) {
            mLocationClient.disableBackgroundLocation(true);
            mLocationClient.stopLocation();
        }
    }


    private static final boolean ENABLED_ONLY = true;
    public static final String GPS_OR_NETWORK_STATE_ERROR = "请检查网络或GPS是否打开";

    public static boolean isCanLocate(Context mContext) {
        if (mContext == null) {
            return false;
        }

        LocationManager mLocationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
        List<String> providers = mLocationManager.getProviders(ENABLED_ONLY);

        return providers != null && (providers.contains(LocationManager.GPS_PROVIDER) ||
                providers.contains(LocationManager.NETWORK_PROVIDER) || providers.contains(LocationManager.PASSIVE_PROVIDER));
    }


    /**
     * 将经纬度转换为度分秒格式
     *
     * @param du 116.418847
     * @return 116°25'7.852324"
     */
    public static String changeToDFM(double du) {
        int du1 = (int) du;
        double tp = (du - du1) * 60;
        int fen = (int) tp;
        //保留6位小数
        String miao = String.format("%.6f", Math.abs(((tp - fen) * 60)));
        return du1 + "°" + Math.abs(fen) + "'" + miao + "\"";
    }

    /**
     * 度分秒转经纬度
     *
     * @param dms 116°25'7.85"
     * @return 116.418847
     */
    public static double changeToDu(String dms) {
        if (dms == null) return 0;
        try {
            dms = dms.replace(" ", "");
            String[] str2 = dms.split("°");
            if (str2.length < 2) return 0;
            int d = Integer.parseInt(str2[0]);
            String[] str3 = str2[1].split("\'");
            if (str3.length < 2) return 0;
            int f = Integer.parseInt(str3[0]);
            String str4 = str3[1].substring(0, str3[1].length() - 1);
            double m = Double.parseDouble(str4);

            double fen = f + (m / 60);
            double du = (fen / 60) + Math.abs(d);
            if (d < 0) du = -du;
            return du;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    public Notification buildNotification(Context context) {
        Notification.Builder builder = null;
        Notification notification = null;
        if (android.os.Build.VERSION.SDK_INT >= 26) {
            //Android O上对Notification进行了修改，如果设置的targetSDKVersion>=26建议使用此种方式创建通知栏
            if (null == notificationManager) {
                notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
            }
            String channelId = context.getPackageName();
            if (!isCreateChannel) {
                NotificationChannel notificationChannel = new NotificationChannel(channelId,
                        NOTIFICATION_CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
                notificationChannel.enableLights(true);//是否在桌面icon右上角展示小圆点
                notificationChannel.setLightColor(Color.BLUE); //小圆点颜色
                notificationChannel.setShowBadge(true); //是否在久按桌面图标时显示此渠道的通知
                notificationManager.createNotificationChannel(notificationChannel);
                isCreateChannel = true;
            }
            builder = new Notification.Builder(context.getApplicationContext(), channelId);
        } else {
            builder = new Notification.Builder(context.getApplicationContext());
        }
        builder.setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle(context.getString(R.string.app_name))
                .setContentText("正在后台运行")
                .setWhen(System.currentTimeMillis());

        if (android.os.Build.VERSION.SDK_INT >= 16) {
            notification = builder.build();
        } else {
            return builder.getNotification();
        }
        return notification;
    }
}
